import server, signal, serial, resources, winreg
regKey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'HARDWARE\\DEVICEMAP\\SERIALCOMM')
index = 0
port = 'COM3'
while True:
  try:
    value, data, type_no = winreg.EnumValue(regKey, index)
    if value.startswith('\\Device\\'):
      port = data
      break
    index += 1
  except OSError:
    break
winreg.CloseKey(regKey)

def sigint(sig, _):
  if sig == signal.SIGINT:
    server.TelnetServer.run = False

try:
  ser = serial.Serial(port, 9600, timeout = 0, write_timeout = 0)
  if ser.is_open:
    signal.signal(signal.SIGINT, sigint)
    server.TelnetServer(lambda x : ser.read(x), lambda x : ser.write(x)).start()
    ser.close()
  else:
    print(resources.resource(resources.Resource.SERIAL_OPEN_ERROR, resources.Language.CHINESE))
except serial.SerialException:
  print(resources.resource(resources.Resource.SERIAL_OPEN_ERROR, resources.Language.CHINESE))